﻿/* AgileFx Version 2.0
 * An open-source framework for rapid development of applications and services using Microsoft.net
 * Developed by: AgileHead
 * Website: www.agilefx.org
 * This component is licensed under the terms of the Apache 2.0 License.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Mvc.Html;
using AgileFx.MVC.FormValidation;
using System.Linq.Expressions;

namespace AgileFx.MVC.Controls
{
    public static partial class HtmlUtil
    {
        private static Dictionary<string, object> GetValidationAttributes(Validation valInfo)
        {
            return GetValidationAttributes(null, valInfo);
        }

        private static Dictionary<string, object> GetValidationAttributes(object htmlAttributes, Validation valInfo)
        {
            Dictionary<string, object> attr = (null == htmlAttributes) ? new Dictionary<string, object>() : GetHtmlAttributes(htmlAttributes);
            if (valInfo != null) valInfo.SetAttributes(attr);
            return attr;
        }

        private static Dictionary<string, object> GetHtmlAttributes(object htmlAttributes)
        {
            var htmlAttr = new Dictionary<string, object>();
            var props = htmlAttributes.GetType().GetProperties();

            foreach (var prop in props)
            {
                var propertyName = !prop.Name.StartsWith("@") ? prop.Name : prop.Name.Substring(1);
                htmlAttr.Add(propertyName, prop.GetValue(htmlAttributes, null));
            }

            return htmlAttr;
        }

        private static IDictionary<string, object> GetFormValidationAttributes(object htmlAttributes)
        {
            var attributes = (null == htmlAttributes) ? new Dictionary<string, object>() : GetHtmlAttributes(htmlAttributes);
            attributes.Add("onsubmit", "return validateForm();");
            return attributes;
        }

        private static string GetPropertyName(LambdaExpression expression)
        {
            if (null == expression) return null;

            //if (expression.Body
            string rhs = expression.Body.ToString();
            int dot = rhs.IndexOf('.');
            var result = (dot != -1) ? rhs.Substring(dot + 1) : null;
            return result;
        }
    }
}
